package admin

import (
	"encoding/json"
	"io/ioutil"
	"net/http"

	"gitee.com/wangxuanbo/soso/chat"
	log "github.com/cihub/seelog"
	"github.com/julienschmidt/httprouter"
)

type Api struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

// Broadcast message to all clients
func Broadcast(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	// Read request body
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		log.Warn("Read request body error. ", err)
		send(w, &Api{Code: 400, Message: "读取Request Body错误"})
		return
	}
	defer r.Body.Close()

	// Parse json
	var message chat.Message
	err = json.Unmarshal(body, &message)
	if err != nil {
		log.Warn("Parse json error. ", err)
		send(w, &Api{Code: 400, Message: "解析Request Body错误"})
		return
	}

	// Do broadcast
	message.FromUser = "系统"
	chat.ChatServer.SendAll(&message)
	send(w, &Api{Code: 200, Message: "内容已广播"})
}

func send(w http.ResponseWriter, api *Api) {
	b, err := json.Marshal(api)
	if err != nil {
		log.Warn("Api Marshal error. ", err)
		return
	}

	_, err = w.Write(b)
	if err != nil {
		log.Warn("Send Response error. ", err)
		return
	}
}
